package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.service.ord.pos.vo.KitePosOfferInstVO;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttachmentDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosContractDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstContract;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;

@Service
public class KitePosContractHandler implements IKitePosSceneHandler {

    @Override
    public void handle(KitePosHandlerContext context) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String downloadFileFlag = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "downloadFile");
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());

        if (KeyConsts.IFTRUE_T.equals(downloadFileFlag)) {
            return;
        }
        if (KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)) {
            context.getPosDto().setContract(Lists.newArrayList());
            return;
        }
        List<KitePosContractDTO> contracts = new ArrayList<>();
        List<KiteOfferInst> offerInsts = Lists.newArrayList();
        Map<String, KitePosOfferInstVO> mainOfferInstMap = context.getPosSceneBO().getMainOfferInstMap();
        Map<String, KitePosOfferInstVO> giftOfferInstMap = context.getPosSceneBO().getGiftOfferInstMap();
        if (!KiteMapUtils.isEmpty(giftOfferInstMap)) {
            Iterator<KitePosOfferInstVO> iterator = giftOfferInstMap.values().iterator();
            while (iterator.hasNext()) {
                KitePosOfferInstVO offerInstVO = iterator.next();
                //融合商品实例
                offerInsts.add(offerInstVO.getOfferInst()); //融合商品实例
            }
        }
        else {
            Iterator<KitePosOfferInstVO> iterator = mainOfferInstMap.values().iterator();
            while (iterator.hasNext()) {
                KitePosOfferInstVO offerInstVO = iterator.next();
                //套餐实例
                offerInsts.add(offerInstVO.getOfferInst()); //套餐实例
            }
        }

        offerInsts.forEach(offerInst -> {
            if (BatchAcceptUtil.isBatchSign(context.getSceneInstId())
                && KiteStringUtils.isNotEmpty(context.getOfferInstId())
                && !KiteStringUtils.equals(offerInst.getOfferInstId(), context.getOfferInstId())) {
                return;
            }
            List<KiteOfferInstContract> offerInstContractRels = querySceneInstService.listOfferInstContracts(
                KiteStringUtils.isEmpty(kiteSceneInst.getCustId()) ? context.getCustId() : kiteSceneInst.getCustId(),
                offerInst.getOfferInstId());
            if (Objects.isNull(offerInstContractRels)) {
                //ErrorConsts.BUSI_CHECK_ERROR.throwOut("合同/受理单信息不能为空");
                offerInstContractRels = new ArrayList<>();
            }

            offerInstContractRels = offerInstContractRels.stream()
                .filter(contract -> !KiteStringUtils.equals(contract.getActionType().name(), ActionType.X.name()))
                .collect(Collectors.toList());
            // 获取删除的合同
            offerInstContractRels.addAll(queryDelContractRelInfo(context.getSceneInstId(),offerInst.getOfferInstId()));
            KiteListUtils.distinctByPropertyName(offerInstContractRels, "instId");
            offerInstContractRels.forEach(offerInstContractRel -> {
                KitePosContractDTO contract = new KitePosContractDTO();
                contract.setInstanceId(offerInstContractRel.getInstId());
                if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(kiteSceneInst.getServiceOfferId())
                    && KeyConsts.IFTRUE_T.equals(querySceneInstService
                    .getExtParameterValue(context.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))) {
                    contract.setInstanceId(CommonUtil.getInstanceId(LocalKeyConsts.HT_INST_CODE, offerInstContractRel.getInstId()));
                }
                contract.setBatchCode(offerInstContractRel.getContractBatchId());
                contract.setName(offerInstContractRel.getContractName());
                contract.setContractCode(offerInstContractRel.getContractNo());
                contract.setChangeType(ChangeTypeUtils.getChangeType(offerInstContractRel.getActionType().name()));
                List<KitePosAttachmentDTO> attachments = new ArrayList<KitePosAttachmentDTO>();

                /* List<KitePosAttachmentDTO> attachments = new ArrayList<KitePosAttachmentDTO>();
                KitePosAttachmentDTO attachement = new KitePosAttachmentDTO();
                  attachement.setCatagory("13"); //合同/受理单-服务协议
                String attachementName = null;
                String attachementUrl = offerInstContractRel.getContractUrl();
                // 合同url中包含"*_*"符号
                boolean splitFlag = KiteStringUtils.contains(offerInstContractRel.getContractUrl(), "*_*");

                if (splitFlag) {
                    attachementName = KiteStringUtils.substring(offerInstContractRel.getContractUrl(),
                        KiteStringUtils.lastIndexOf(offerInstContractRel.getContractUrl(), "*_*") + 3);
                    attachementUrl = KiteStringUtils.substring(attachementUrl, 0,
                        KiteStringUtils.lastIndexOf(offerInstContractRel.getContractUrl(), "*_*"));
                }
                else if (KiteStringUtils.isNotEmpty(offerInstContractRel.getAttachmentName())) {
                    // 通过接口报文回填值时，会将合同附件名称放到offerInstContractRel.attachmentName
                    attachementName = offerInstContractRel.getAttachmentName();
                }
                else {
                    attachementName = KiteStringUtils.substring(offerInstContractRel.getContractUrl(),
                        KiteStringUtils.lastIndexOf(offerInstContractRel.getContractUrl(), "/") + 1);
                }
                if (splitFlag || KiteStringUtils.contains(offerInstContractRel.getContractUrl(), "|")) {
                    String[] ac = attachementUrl.split("\\|");
                    for (int i = 0; i < ac.length; i++) {
                        // url包含"*_*"的直接取上面切分好的名称,否则说明url是用"|"分隔的多个附件,那么按照切分的url动态解析
                        String tempAttachName = splitFlag ? attachementName : KiteStringUtils.substring(ac[i], KiteStringUtils.lastIndexOf(ac[i], "/") + 1);
                        KitePosAttachmentDTO attachements = new KitePosAttachmentDTO();
                        attachements.setCatagory("13");
                        attachements.setName(tempAttachName);
                        attachements.setUrl(ac[i]);
                        attachments.add(attachements);
                        contract.setAttachments(attachments);
                    }
                }else{
                    attachement.setName(attachementName);
                    attachement.setUrl(attachementUrl);
                    attachments.add(attachement);
                    contract.setAttachments(attachments);
                }*/
                List<KitePosAttachmentDTO> attachment = new ArrayList<KitePosAttachmentDTO>();
                if(!KiteObjectUtils.isEmpty(offerInstContractRel.getAttachments())){
                    String oldattachment = JSONObject.toJSONString(offerInstContractRel.getAttachments());
                    attachment=JSONObject.parseArray(oldattachment, KitePosAttachmentDTO.class);
                    attachment.stream().forEach(s->s.setCatagory("13"));
                    contract.setAttachments(attachment);
                }
                Date startTime = offerInstContractRel.getBeginDate();
                contract.setContractType(offerInstContractRel.getContractType());
                //新增合同关系，不需要传开始时间，用户中心会默认竣工时间
                if (Objects.nonNull(startTime) && !KiteStringUtils.equals(contract.getChangeType(), ChangeTypeUtils.CHANGE_TYPE_A)) {
                    contract.setStartTime(KiteDateUtils.formatDate(startTime,KiteDateUtils.DATE_TIME_FORMAT_14));
                }
                Date endTime = offerInstContractRel.getEndDate();
                //新增和删除都可以不用失效时间，用户中心会有默认时间
                if (Objects.nonNull(endTime) && !KiteStringUtils.equalsAny(contract.getChangeType(), ChangeTypeUtils.CHANGE_TYPE_D,ChangeTypeUtils.CHANGE_TYPE_A)) {
                    contract.setEndTime(KiteDateUtils.formatDate(endTime,KiteDateUtils.DATE_TIME_FORMAT_14));
                }

                /*this.addInstanceIdAttr(context.getSceneInstId(), "instanceId", offerInstContractRel.getInstId(),
                    contract);*/

                contracts.add(contract);
            });
        });

        context.getPosDto().setContract(contracts);
    }

    // 获取删除的合同
    private List<KiteOfferInstContract> queryDelContractRelInfo(String sceneInstId, String offerInstId) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        List<KiteOfferInstContract> delContractList = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.OFFER_INST_CONTRACT));
        delContractList.removeIf(delContract -> !KiteStringUtils.isEqual(delContract.getOfferInstId(), offerInstId) || (
            !KiteStringUtils.isEqual(delContract.getActionType().name(), ActionType.D.name()) && KiteStringUtils
                .isEqual(delContract.getOfferInstId(), offerInstId)));

       return delContractList;
    }
}
